package com.netx.cubigraf.entities;
import com.netx.data.DatabaseException;
import com.netx.data.Entity;
import com.netx.data.ValueList;
import com.netx.generics.sql.Row;
import com.netx.generics.sql.Table;


public class Tasks extends Entity {

	public Tasks() {
	}
	
	public long addTask(long entityId, char type) throws DatabaseException {
		ValueList values = new ValueList();
		values.addValue("entity_id", entityId);
		values.addValue("task_type", type);
		return insert(values);
	}

	public Row getNext(char taskType) throws DatabaseException {
		synchronized(getConnection()) {
			Table t = getConnection().select("task_id, entity_id, task_type FROM tasks WHERE task_type='"+taskType+"' AND failed=0 AND locked=0 LIMIT 1");
			if(t.isEmpty()) {
				return null;
			}
			else {
				Row task = t.getRow(0);
				ValueList values = new ValueList();
				values.addValue("locked", true);
				update(task.getLong(1), values);
				return task;
			}
		}
	}
	
	public void removeTask(long taskId) throws DatabaseException {
		delete(taskId);
	}
	
	public void markAsFailed(long taskId) throws DatabaseException {
		ValueList values = new ValueList();
		values.addValue("failed", true);
		values.addValue("locked", false);
		update(taskId, values);
	}
	
	public void restartTasks(char taskType) throws DatabaseException {
		ValueList values = new ValueList();
		values.addValue("failed", false);
		update(values, "task_type='"+taskType+"' AND locked=0");
	}
}
